package com.lanxiao.cloud.gateway.provider;

import com.lanxiao.cloud.gateway.api.GatewayRouteDubboApi;
import com.lanxiao.cloud.gateway.api.dto.GatewayRouteDubboDto;
import java.util.ArrayList;
import java.util.List;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

/**
 * @author ：qiaoliang
 * @date ：2021-08-24
 */
@Component
@Primary
public class GatewaySwaggerProvider implements SwaggerResourcesProvider {

  public static final String API_URI = "/v2/api-docs";
  @DubboReference
  private GatewayRouteDubboApi gatewayRouteDubboApi;

  @Override
  public List<SwaggerResource> get() {
    List<SwaggerResource> resources = new ArrayList<>();
    final List<GatewayRouteDubboDto> gatewayRouteDtoList = gatewayRouteDubboApi.all();
    //结合配置的route-路径(Path)，和route过滤，只获取有效的route节点
    gatewayRouteDtoList.forEach(predicateDefinition -> resources.add(swaggerResource(
        predicateDefinition.getServiceId(),
        predicateDefinition.getPredicates().replace("/**", API_URI))));
    return resources;
  }

  private SwaggerResource swaggerResource(String name, String location) {
    SwaggerResource swaggerResource = new SwaggerResource();
    swaggerResource.setName(name);
    swaggerResource.setLocation(location);
    swaggerResource.setSwaggerVersion("2.0");
    return swaggerResource;
  }

}
